//
//  ZJProductController.m
//  Lottery
//
//  Created by ZJ on 2018/8/16.
//  Copyright © 2018年 iCatch Technology Inc. All rights reserved.
//

#import "ZJProductController.h"
#import "ZJProduct.h"
#import "ZJProductCell.h"

@interface ZJProductController ()

@property (nonatomic, strong) NSArray *products;

@end

@implementation ZJProductController

static NSString * const reuseIdentifier = @"Cell";

// 懒加载 解析
- (NSArray *)products {
    if (_products == nil) {
        // 1.获取文件路径
        NSString *path = [[NSBundle mainBundle] pathForResource:@"more_project" ofType:@"json"];
        
        // 2.把文件转化成 data
        NSData *data = [NSData dataWithContentsOfFile:path];
        
        // 3.通过 data 转化成 array
        NSArray *tempArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        // 4.初始化一个可变数组
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:tempArray.count];
        
        // 5.遍历临时数组 获取字典
        for (NSDictionary *dict in tempArray) {
            // 6.通过字典转模型
            ZJProduct *p = [ZJProduct productWithDict:dict];
            
            // 7.把模型添加到可变数组当中
            [array addObject:p];
        }
        
        // 8.赋值
        _products = array.copy;
    }
    
    return _products;
}

- (instancetype)init {
    // 创建 layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    // 设置 layout 参数
    
    // item大小
    layout.itemSize = CGSizeMake(80, 80);
    // item左右最小的距离
    layout.minimumInteritemSpacing = 0;
    // 组内边距
    layout.sectionInset = UIEdgeInsetsMake(16, 0, 0, 0);
    
    return [super initWithCollectionViewLayout:layout];
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-designated-initializers"
- (instancetype)initWithCollectionViewLayout:(UICollectionViewLayout *)layout {
    return [self init];
}
#pragma clang diagnostic pop

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Register cell classes
    // 注册单元格
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([ZJProductCell class]) bundle:nil];
    [self.collectionView registerNib:nib forCellWithReuseIdentifier:reuseIdentifier];
    
    // Do any additional setup after loading the view.
    // 修改 collView 的背景颜色
    self.collectionView.backgroundColor = [UIColor colorWithRed:0.91 green:0.93 blue:0.93 alpha:1.0];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

// collectionView 点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    // 点击这个 cell 的模型
    ZJProduct *p = self.products[indexPath.row];
    
//    NSLog(@"%@", p.title);
    // 获取 app 对象
    UIApplication *app = [UIApplication sharedApplication];
    
    // 获取 本地程序的 url
    NSURL *appUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@://%@", p.customUrl, p.ids]];
    
    // 获取 AppStore  url
    NSURL *storeUrl = [NSURL URLWithString:p.url];
    
    // ------- 跳转到应用程序 -------------
    // ----- iOS9 -----
    if (![app openURL:appUrl]) {
        // 如果本地没有这个应用程序 那么打开 AppStore 并且显示相应程序的页面
        [app openURL:storeUrl];
    }
    // ----- iOS9 -----
    
//    // ----- iOS8 -----
//    // 判断 本地是否有这个应用程序 (本地的应用程序是否能被打开)
//    if ([app canOpenURL:appUrl]) {
//        // 如果本地有这个应用程序 那么打开
//        [app openURL:appUrl];
//    } else {
//        // 如果本地没有这个应用程序 那么打开 AppStore 并且显示相应程序的页面
//        [app openURL:storeUrl];
//    }
//    // ----- iOS8 -----
}

#pragma mark <UICollectionViewDataSource>
// 有多少组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

// 某一组有多上行
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.products.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 缓存池找
    ZJProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    // Configure the cell
    // 把模型(数据)传给 cell
    cell.product = self.products[indexPath.row];
    
    return cell;
}

#pragma mark <UICollectionViewDelegate>

/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
*/

@end
